package hlhj.fhp.supreme.activitys

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.media.MediaMetadataRetriever
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.WindowManager
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.qiniu.android.common.FixedZone
import com.qiniu.android.http.ResponseInfo
import com.qiniu.android.storage.*
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import fhp.hlhj.giantfold.utils.LogUtil
import hlhj.fhp.supreme.BaseAty
import hlhj.fhp.supreme.Contents
import hlhj.fhp.supreme.R
import hlhj.fhp.supreme.customview.ClassTypePop
import hlhj.fhp.supreme.customview.UpProgressDialog
import hlhj.fhp.supreme.javabean.BaseBean
import hlhj.fhp.supreme.javabean.ClassTypeBean
import hlhj.fhp.supreme.javabean.QNBean
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.JsonCallBack
import hlhj.fhp.supreme.utils.MyUtils
import kotlinx.android.synthetic.main.activity_cover_aty.*
import org.json.JSONObject
import java.io.File
import java.util.ArrayList

class CoverAty : BaseAty(), ClassTypePop.OnClassTypeClickListnerer {
    private lateinit var cid:String
    private lateinit var lid:String
    private lateinit var coverPop:ClassTypePop
    private lateinit var upDialog:UpProgressDialog
    private var qnToken=""
    private var vHash=""
    private var iHash=""
    override fun getContentId(): Int {
        return R.layout.activity_cover_aty
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
    }
     val PICK_VIDEO: Int=1

    override fun initView() {
        upDialog= UpProgressDialog(this)
        OkGo.post<ClassTypeBean>(Urls.BaseUrl+Urls.COVER_TYPE_LIST)
                .execute(object :JsonCallBack<ClassTypeBean>(this){
                    override fun onSuccess(response: Response<ClassTypeBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            coverPop= ClassTypePop(this@CoverAty,bean?.data.cat as ArrayList<ClassTypeBean.DataBean.CatBean>,this@CoverAty)
                            tvRate.text="4、审核通过后的您可从销售净额中提成${bean?.data!!.reward_rate}%；"
                        }
                    }
                })
        OkGo.post<QNBean>(Urls.BaseUrl+Urls.QNTOKEN)
                .params("type",1)
                .execute(object :JsonCallBack<QNBean>(this){
                    override fun onSuccess(response: Response<QNBean>?) {
                        val qnBean = response?.body()
                        if (qnBean?.code==1){
                            qnToken=qnBean.data.token
                        }else{
                            MyUtils.toast("获取七牛参数失败")
                            finish()
                        }
                    }
                })
// 重用uploadManager。一般地，只需要创建一个uploadManager对象


    }

    override fun initListener() {
        btCommit.setOnClickListener {
            if (etTittle.text.isEmpty()||etType.text.isEmpty()||etVideoName.text.isEmpty()||etPrice.text.isEmpty()||etDes.text.isEmpty()){
                MyUtils.toast("请完善信息")
            }else{
                OkGo.post<BaseBean>(Urls.BaseUrl+Urls.PUB_CLASS)
                        .params("cid",cid)
                        .params("level_id",lid)
                        .params("title",etTittle.text.toString())
                        .params("src",vHash)
                        .params("img",iHash)
                        .params("desc",etDes.text.toString())
                        .params("money",etPrice.text.toString())
                        .params("type",1)
                        .execute(object :JsonCallBack<BaseBean>(this@CoverAty){
                            override fun onSuccess(response: Response<BaseBean>?) {
                                val bean = response?.body()
                                if (bean?.code==1){
                                    MyUtils.toast("提交成功")
                                    finish()
                                }else{
                                    MyUtils.toast("提交失败")
                                    finish()
                                }
                            }
                        })
            }
        }
        btExit.setOnClickListener {
            finish()
        }
        btType.setOnClickListener {
//            MyUtils.toast("点击")
            if (coverPop.isShowing){
                coverPop.dismiss()
            }else{
                coverPop.showAsDropDown(btType)
            }
        }
        btVideo.setOnClickListener {
            Matisse.from(this)
                    .choose(MimeType.ofVideo())
                    .showSingleMediaType(true)
                    .countable(true)
                    .maxSelectable(1)
                    .spanCount(3)
//                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .theme(R.style.Matisse_Dracula)
                    .imageEngine( GlideEngine())
                    .forResult(PICK_VIDEO);
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!= Activity.RESULT_OK)return
        if (requestCode==PICK_VIDEO){
            val obtainPathResult = Matisse.obtainPathResult(data)
            LogUtil.log(obtainPathResult[0])
            val file = File(obtainPathResult[0])
            val media = MediaMetadataRetriever()
            media.setDataSource(file.path)
            LogUtil.logi("是否为空${media.getFrameAtTime()}")
            val imageFile = MyUtils.createImageFile(media.frameAtTime)
            etVideoName.setText(file.name)
            /**
             * 图片上传
             */
            val ma = UploadManager()
            ma.put(imageFile,null,qnToken,object :UpCompletionHandler{
                override fun complete(key: String?, info: ResponseInfo?, response: JSONObject?) {
                    if (info!!.isOK){
                        LogUtil.logi("图片的hash${response.toString()}")
                        iHash=response?.getString("hash")!!
                    }else{
                        MyUtils.toast("上传失败${info?.error}")
                    }

                }
            },null)
            /**
             * 视频上传
             */
            val manager = UploadManager()
            val option=UploadOptions(null,null,false,object :UpProgressHandler{
                override fun progress(key: String?, percent: Double) {
                    if (upDialog.isShowing){
                        upDialog.setProgress(percent)
                    }else{
                        upDialog.show()
                    }
                }
            },null)
            manager.put(file,null,qnToken, object :UpCompletionHandler{
                override fun complete(key: String?, info: ResponseInfo?, response: JSONObject?) {
                    vHash=response?.getString("hash")!!
                    upDialog.dismiss()
                }
            },option)
        }
    }

    override fun onClassClick(cid: String, lid: String, name: String) {
        this.cid=cid
        this.lid=lid
        etType.setText(name)
    }
}
